package net.wangds.web.aop;

import net.wangds.web.entrypoint.BaseResp;
import net.wangds.log.helper.LogHelper;
import net.wangds.filler.Filler;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;

/**
 * 填充切面.
 * <p>对http应答中的对象进行字段填充.</p>
 */
@Aspect
@Component
@SuppressWarnings("unused")
public class FillerAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void responseField(){}


    @SuppressWarnings({ "ConstantConditions"})
    @AfterReturning(returning = "res", pointcut = "responseField()")

    public void doAfterReturning(Object res) {

        if(res instanceof BaseResp){
            Object body = ((BaseResp) res).getBody();
            if(body!=null) {
                boolean is_array = body.getClass().isArray();
                if (body instanceof Collection||is_array) {

                    if(is_array){
                        body = Arrays.asList((Object[])body);
                    }

                    Collection<?> cl = ((Collection<?>)body);
                    Filler<Object> filler = null;
                    if(!cl.isEmpty()){
                        //找到第一个可以获得填充器的对象
                        for(Object c:cl){
                            if(c!=null){
                                filler = Filler.findFiller(c.getClass());
                                if(filler!=null){
                                    break;
                                }
                            }
                        }
                        //对每个元素进行一次填充
                        if(filler!=null){
                            for(Object c:cl){
                                try{
                                    filler.fill(c);
                                }catch (Exception e){
                                    LogHelper.warn(e);
                                }
                            }
                        }
                    }
                }else{
                    //处理非集合数据.
                    Filler<Object> filler = Filler.findFiller(body.getClass());

                    if(filler!=null){
                        try{
                            filler.fill(body);
                        }catch(Exception e){
                            LogHelper.warn(e);
                        }
                    }
                }
            }

        }

    }

}
